package com.yunju.xuexin.xuexincrawler.Service;

import com.yunju.xuexin.xuexincrawler.Model.RestVo;
import com.yunju.xuexin.xuexincrawler.biz.XuexinService;
import com.yunju.xuexin.xuexincrawler.utils.SpringContextUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@RestController
public class XuexinCrawler {

    private Map<String, XuexinService> xuexinServiceStore = new ConcurrentHashMap<>();

    /**
     * 登陆
     * @param sessionid
     * @param username
     * @param passwd
     * @param verifyCode
     * @return
     */
    @RequestMapping(value = "/xuexin", method = RequestMethod.GET)
    public RestVo get(@RequestParam("sessionid") String sessionid, @RequestParam("username") String username, @RequestParam("passwd") String passwd, @RequestParam("verifyCode") String verifyCode) {
        if (StringUtils.isEmpty(sessionid) || xuexinServiceStore.get(sessionid) == null) {
            XuexinService xuexinService = (XuexinService) SpringContextUtil.getBean(XuexinService.class);
            RestVo restVo = xuexinService.login(username, passwd);
            if (restVo.isVerifyCode()) {
                xuexinServiceStore.put(restVo.getSessionId(), xuexinService);
            }
            return restVo;
        } else {
            XuexinService xuexinService = xuexinServiceStore.get(sessionid);
            RestVo restVo = xuexinService.reLogin(username, passwd, verifyCode);
            if (restVo.isVerifyCode()) {
                xuexinServiceStore.put(restVo.getSessionId(), xuexinService);
            }else{
                xuexinServiceStore.remove(restVo.getSessionId());
            }
            return restVo;
        }

    }

    /**
     * 刷新验证码
     * @param sessionid
     * @return
     */
    @RequestMapping(value = "/xuexin/freshcaptcha", method = RequestMethod.GET)
    public  RestVo freshCaptcha(@RequestParam("sessionid") String sessionid){
        XuexinService xuexinService = xuexinServiceStore.get(sessionid);
        try {
            String captcha = xuexinService.freshCode();
            return RestVo.build().setVerifyCode(true).setObj(captcha).setResCode(0);
        } catch (IOException e) {
            e.printStackTrace();
            return  RestVo.build().setVerifyCode(true).setMsg("刷新失败,请重试").setResCode(0);
        }

    }



}
